var $ = require('jquery');
var actions = require('../actions');
var _userCache = {};
var _userStoreCache = {};
/**
 * 获取当前用户信息，如果用户信息不存在，重新获取，返回null,同时触发UPDATED_USER_INFO事件
 * @param userId
 * @returns {*}
 */
module.exports.getUserInfo = function (userId) {
  var defer = $.Deferred();
  console.log('更新用户信息:', userId);
  if (_userCache[userId]) {
    defer.resolve(_userCache[userId]);
  } else {
    $.get('/webim/user/' + userId).done(function (data) {
      console.log('获取用户信息成功', data);
      _userCache[userId] = data.result;
      defer.resolve(data.result);
    }).fail(function (err) {
      console.error('获取用户信息失败', err);
      defer.reject(err);
    });
  }
  return defer;
};

var ossConfigCache = {};
module.exports.getOssConfig = function () {
  var defer = $.Deferred();
  var now = new Date().getTime();
  if (ossConfigCache.expires && ossConfigCache.expires > now + 10 * 60 * 1000) {
    defer.resolve(ossConfigCache);
    return defer;
  }

  return $.getJSON('/webim/misc/oss_signature').then(function (result) {
    ossConfigCache = result;
    return ossConfigCache;
  });
};

module.exports.getHistoryMessages = function (targetId, timestamp) {
  $.getJSON('/webim/message/history?target=' + targetId + '&before=' + timestamp || '').then(function (data) {
    return data.result;
  });
};

/**
 * 批量获取用户在线状态
 * @param ids
 */
module.exports.getOnlineStatus = function (ids) {
  var query = ids.map(function (id) {
    return 'id=' + id;
  });
  
  var expires = new Date().getTime() - 30 * 60 * 1000;
  query.push('expires=' + expires);

  var search = query.join('&');
  return $.getJSON('/webim/user/online_status/batch?' + search).then(function (data) {
    return data.result;
  });
};


